package com.kandinfo.survey.uploadquesiton.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.converter.FontReplacer;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.converter.WordToHtmlUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.kandinfo.base.common.util.AppConfigUtil;
import com.kandinfo.survey.uploadquesiton.dto.ParserDto;
import com.kandinfo.survey.uploadquesiton.service.UploadQuesService;

@Service
public class UploadQuesServiceImpl implements UploadQuesService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Boolean uploadFile(ParserDto dto) throws IllegalStateException, IOException {
        String htmlPath = AppConfigUtil.getConfig("word.upload") + File.separator + "html";// 临时html文件保存路径
        checkAndCreatePath(htmlPath);
        String wordPath = AppConfigUtil.getConfig("word.upload") + File.separator + "word"; // word保存路径
        checkAndCreatePath(wordPath);
        FileOutputStream fos = null;

        // 读取文件流
        InputStream in = dto.getFile().getInputStream();
        // 获取文件名 (不包含 后缀)
        final String wordFileName = dto.getFile().getOriginalFilename().substring(0,
                dto.getFile().getOriginalFilename().lastIndexOf('.'));
        // 保存word文件到服务器
        saveFile(fos, in, wordPath, wordFileName);
        // multipartFile -> file
        File file = File.createTempFile("123", "321");
        dto.getFile().transferTo(file);

        try {
            // 载入
            final HWPFDocumentCore wordDocument = WordToHtmlUtils.loadDoc(file);
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                    DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
            // 格式
            wordToHtmlConverter.setFontReplacer(new FontReplacer() {
                @Override
                public Triplet update(Triplet original) {
                    return new Triplet();
                }
            });
            // 输出流
            wordToHtmlConverter.processDocument(wordDocument);

            String path = htmlPath + File.separator + wordFileName + ".html";
            FileWriter out = new FileWriter(path);
            try {
                DOMSource domSource = new DOMSource(wordToHtmlConverter.getDocument());
                StreamResult streamResult = new StreamResult(out);
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer serializer = tf.newTransformer();
                serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                serializer.setOutputProperty(OutputKeys.INDENT, "yes");
                serializer.setOutputProperty(OutputKeys.METHOD, "html");
                serializer.transform(domSource, streamResult);
            } catch (Exception e) {
                logger.error("HTML CREATE ERROR:", e);
            } finally {
                out.close();
            }

            // 解析
            Document document = Jsoup.parse(new File(path), "UTF-8", "word解析");
            String[] string = document.html().split("@@@");
            for (String string2 : string) {
                Document documentq = Jsoup.parse(string2);
                // parerQuestion(documentq, dto, wordFileName);
            }
        } catch (Exception e) {
            logger.error("PARSER WORD ERROR:", e);
            return false;
        } finally {
            file.delete();
        }

        return true;
    }

    /**
     * 检查是都存在路径，若没有创建路径
     * 
     * @param path
     *            路径
     */
    public void checkAndCreatePath(String path) {
        File file = new File(path);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    /**
     * 保存文件
     * 
     * @param fos
     * @param in
     * @param wordFileName
     * @throws IOException
     */
    public void saveFile(FileOutputStream fos, InputStream in, String filePath, String fileName) {
        try {
            fos = new FileOutputStream(new File(filePath + File.separator + fileName + ".doc"));
            fos.write(IOUtils.toByteArray(in));
        } catch (IOException e) {
            logger.error("", e);
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                logger.error("", e);
            }
        }
    }

    @Override
    public void parseExcel() throws IOException {
        InputStream input = new FileInputStream("as"); // 建立输入流
        Workbook wb = null;
        wb = new HSSFWorkbook(input);
        Sheet sheet = wb.getSheetAt(0); // 获得第一个表单
        Iterator<Row> rows = sheet.rowIterator(); // 获得第一个表单的迭代器
        while (rows.hasNext()) {
            Row row = rows.next(); // 获得行数据
            System.out.println("Row #" + row.getRowNum()); // 获得行号从0开始
            Iterator<Cell> cells = row.cellIterator(); // 获得第一行的迭代器
            while (cells.hasNext()) {
                Cell cell = cells.next();
                System.out.println("Cell #" + cell.getColumnIndex());
                switch (cell.getCellType()) { // 根据cell中的类型来输出数据
                case HSSFCell.CELL_TYPE_NUMERIC:
                    System.out.println(cell.getNumericCellValue());
                    break;
                case HSSFCell.CELL_TYPE_STRING:
                    System.out.println(cell.getStringCellValue());
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    System.out.println(cell.getBooleanCellValue());
                    break;
                case HSSFCell.CELL_TYPE_FORMULA:
                    System.out.println(cell.getCellFormula());
                    break;
                default:
                    System.out.println("unsuported sell type");
                    break;
                }
            }
        }
    }
}
